//
//  MHNewsViewController.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHNewsViewController.h"
#import "Lib.h"
#import "Contants.h"
#import "News.h"
#import "MHNewsCell.h"
#import "UIImageView+WebCache.h"
#import "MHNewsDetailViewController.h"
#import "MHGameHotSlider.h"

@interface MHNewsViewController ()


@end

@implementation MHNewsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.currentIndex = 0;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
//    [self reloadData];
}

- (void)refresh {
    [self.data removeAllObjects];
    self.data = nil;
    [self reloadData];
}

- (void)loadingMore {
    [self loadMore];
}

- (void)delayReload {
    [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.5];
}

- (void)reloadData {
    if (self.data) {
        return;
    }
    [self loadFromIndex:0];
}

- (void)loadMore {
    [self loadFromIndex:self.currentIndex];
}

- (void)loadFromIndex: (int )index {
    [Lib showLoadingView];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray* arr = [News newsArrayFromUrl:[Contants urlForKey:[NSString stringWithFormat:kServiceNewsFormat, 0, index, 10]]];
        if (index == 0 || !self.data) {
            self.data = [NSMutableArray arrayWithArray:arr];
        }
        else {
            for (id news in arr) {
                [self.data addObject:news];
            }
        }
        self.currentIndex = index + 1;
        self.hotData = [News getHotNews];
        
        // main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self stopLoading];
            [self stopLoadingMore];
            [self.tableView reloadData];
        });
    });
}

#pragma mark -UITableView Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.data.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* CellIndentifier = @"Cell";
    if (indexPath.section == 0) {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] init];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            self.hotSlider = [MHGameHotSlider sliderFromNib];
            
            NSMutableArray* viewsArray = [[NSMutableArray alloc] init];
            for (News* news in self.hotData) {
                NSURL* url = [Contants getImageUrl:news.imagePath width:320 height:120];
                if (url) {
                    [viewsArray addObject:url];
                }
            }
            [self.hotSlider.infiSlider setViewsArray:viewsArray];
            
            [cell.contentView addSubview:self.hotSlider];
        }
        return cell;
    }
    else {
        MHNewsCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
        if (!cell) {
            cell = [MHNewsCell cellFromNib];
        }
        // configure cell
        News* news = [self.data objectAtIndex:indexPath.row];
        [cell.imagePath setImageWithURL:[Contants getImageUrl:news.imagePath width:120 height:100]];
        cell.title.text = news.title;
        cell.lead.text = news.lead;
        cell.publishDate.text = news.publishDate;
        return cell;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 132;
    }
    return 90;
}


#pragma mark - UITableView Delegate 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        News* news = [self.data objectAtIndex:indexPath.row];
        NSLog(@"news id: %d detail: %@", news.newsId, news.content);
        if (news.content && ![news.content isKindOfClass:[NSNull class]] && news.content.length > 0) {
            MHNewsDetailViewController* vc = [[MHNewsDetailViewController alloc] initWithNibName:@"MHNewsDetailViewController" bundle:nil];
            vc.htmlString = news.content;
            [self.navigationController pushViewController:vc
                                                 animated:YES];
        }
        else
        {
            [Lib showLoadingView];
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                News* n = [News getDetailNews:[NSString stringWithFormat:@"%d", news.newsId]];
              
                // main thread
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Lib removeLoadingView];
                    if (n.urlDetail) {
                        MHNewsDetailViewController* vc = [[MHNewsDetailViewController alloc] initWithNibName:@"MHNewsDetailViewController" bundle:nil];
                        vc.htmlString = n.content;
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                });
            });
        }
    }
}


@end
